<template>

  <div class="container">
    <van-nav-bar
        title="预订房间"
        left-text="返回"
        left-arrow
        @click-left="back"
    />

    <div class="dv-img" v-if="store.userRoom.hotelRoom.type === 1">
      <van-image
          width="100%"
          height="100%"
          fit="cover"
          src="src/image/room1.png"
          @click="showImage1()"
          style="padding: 10px"
      />
    </div>

    <div class="dv-img" v-if="store.userRoom.hotelRoom.type === 2">
      <van-image
          width="100%"
          height="100%"
          fit="cover"
          src="src/image/room2.png"
          @click="showImage2()"
          style="padding: 10px"
      />
    </div>

    <div class="dv-img" v-if="store.userRoom.hotelRoom.type === 3">
      <van-image
          width="100%"
          height="100%"
          fit="cover"
          src="src/image/room3.png"
          @click="showImage3()"
          style="padding: 10px"
      />
    </div>

    <div class="dv-swipeImg" v-if="store.userRoom.hotelRoom.type === 4">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item
            class="van-swipe-item"
            v-for="image in images"
            :key="image"
            @click="showImage4()"
        >
          <img :src="image" class="swipe-img" alt="error"/>
        </van-swipe-item>
      </van-swipe>
    </div>

    <div class="dv-msg">
      <van-cell-group style="margin-top: 20px">
        <van-cell class="cell_label" title="房间名" title-style="text-align: left">
          <template #value>
            <div style="color: #535bf2;">{{store.userRoom.hotelRoom.name}}</div>
          </template>
        </van-cell>

        <van-cell title="位置" title-style="text-align: left">
          <template #value>
            <div style="color: #535bf2;">{{store.userRoom.hotelRoom.position}}</div>
          </template>
        </van-cell>

        <van-cell title="价格" title-style="text-align: left">
          <template #value>
            <div style="color: red">{{store.userRoom.hotelRoom.price}}元/天</div>
          </template>
        </van-cell>

        <van-cell title="入住时间" title-style="text-align: left">
          <template #value>
            <div style="color: #535bf2;">{{store.userRoom.startMonth}}月{{store.userRoom.startDay}}日-{{store.userRoom.endMonth}}月{{store.userRoom.endDay}}日</div>
          </template>
        </van-cell>

        <van-cell title="剩余天数" title-style="text-align: left">
          <template #value>
            <div style="color: #535bf2;">{{store.userRoom.restDays}}天</div>
          </template>
        </van-cell>

        <van-cell title="您的评分" title-style="text-align: left">
          <template #value>
            <van-rate v-model="roomRate.rate" style="display: flex; justify-content: flex-end; height: 25px" allow-half></van-rate>
            <van-button type="primary" size="small" @click="changeRate()">修改</van-button>
          </template>
        </van-cell>

        <van-cell title-style="text-align: left">
          <template #title>
            <div v-if="store.userRoom.hotelRoom.type === 1">当您选择我们的酒店房间，您将体验到舒适和便利的完美结合。每间房间都精心布置，配备现代化设施，确保您的住宿体验无比愉快。无论是短期商务旅行还是休闲度假，我们的房间都将是您旅途中温馨的家。</div>
            <div v-if="store.userRoom.hotelRoom.type === 2">欢迎来到我们高端酒店的奢华空间，这里融合了现代设计与经典风格，为您提供无与伦比的住宿体验。每间房间均采用精选的豪华家具和顶级的设施，让您尽情享受舒适与便利。无论您是来商务出差还是休闲度假，我们都致力于为您打造一个难忘的居住环境，让您感受到尊贵与独特的待遇。</div>
            <div v-if="store.userRoom.hotelRoom.type === 3">步入我们的豪华酒店房间，您将沉浸于无与伦比的奢华体验之中。每一处细节都展现着精湛的工艺和豪华的设计，为您营造出一个令人心驰神往的居住空间。高端的家具与装饰品搭配，使房间散发出独特的品味与魅力。无论是宁静的休息还是社交与会客，我们的豪华房间都将成为您尊贵生活的完美象征。</div>
            <div v-if="store.userRoom.hotelRoom.type === 4">欢迎来到我们精心设计的打折酒店房间，一个融合现代风格与温馨氛围的理想选择。每间房间均设有舒适的床铺、豪华的浴室以及设施齐全的便利设施，为您的住宿体验提供极致舒适。限时特惠折扣，让您享受奢华住宿，却不必支付高昂价格。</div>
          </template>
        </van-cell>

      </van-cell-group>
    </div>

  </div>
  <van-submit-bar
      :price="store.userRoom.hotelRoom.price * 100"
      button-text="提交订单"
      @submit="onSubmit">
    <template #tip>
      可以使用账户余额支付：点击查看<span @click="onClickLink" style="color: #535bf2">我的钱包</span>
    </template>

    <van-checkbox v-model="checked" @click="roomCollect()">
      收藏
      <template #icon="props">
        <img class="img-icon" :src="props.checked ? activeIcon : inactiveIcon"  alt="error"/>
      </template>
    </van-checkbox>
  </van-submit-bar>

  <!-- 圆角弹窗（底部） -->
  <van-popup
      v-model:show="showPay"
      round
      closeable
      position="bottom"
      :style="{ height: '35%' }"
  >
    <template #default>
      <van-radio-group style="margin-top: 30px" v-model="order.payType">
        <van-cell-group inset>
          <van-cell>
            <div style="text-align: center">
              根据您的vip等级,实际支付的金额为{{(formattedPrice * order.days).toFixed(2)}}元
            </div>
          </van-cell>

          <van-cell icon="notes" title="续费天数">
            <template #value>
              <van-stepper v-model="order.days" theme="round" button-size="22" disable-input />
            </template>
          </van-cell>

          <van-cell icon="shop-o" title="钱包支付" clickable @click="order.payType = '1'">
            <template #right-icon>
              <van-radio name="1" />
            </template>
          </van-cell>
          <van-cell icon="alipay" title="支付宝支付" clickable @click="order.payType = '2'">
            <template #right-icon>
              <van-radio name="2" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
      <div style="margin-top: 10px;margin-left: 5%;width: 90%">
        <van-button block round type="primary" @click="addPay">确认支付</van-button>
      </div>
    </template>
  </van-popup>

</template>

<script setup>

import {showDialog, showImagePreview, showNotify, showToast} from "vant";
import {onMounted, ref} from "vue";

const discountPrice = ref(0.0);
const formattedPrice = ref("");
const vipMessage = ref("")
const showPay=ref(false)
const checked = ref();
const activeIcon = 'https://fastly.jsdelivr.net/npm/@vant/assets/user-active.png'
const inactiveIcon = 'https://fastly.jsdelivr.net/npm/@vant/assets/user-inactive.png'
const images = [
  'src/image/room2.png',
  'src/image/room1.png',
  'src/image/room3.png'
];
const order = ref({
  userId:0,
  roomId:0,
  payType:'',
  vipType:0,
  price:0.0,
  days:0
})

const roomRate = ref({
  rate:0.0,
  roomId:0
})

// 导入useRouter使用路由
import { useRouter } from "vue-router";
// 声明变量
const router = useRouter()

import axios from "axios";
import {post, get} from "../util/request.js";

// 导入pinia
import {useStore} from "../pinia/index.js";
// 声明pinia
const store = useStore();

const back = () => {
  window.location.reload()
  history.back();
}

const showImage1 = () => {
  showImagePreview([
    'src/image/room1.png'
  ])
}

const showImage2 = () => {
  showImagePreview([
    'src/image/room2.png'
  ])
}

const showImage3 = () => {
  showImagePreview([
    'src/image/room3.png'
  ])
}

const showImage4 = () => {
  showImagePreview([
    'src/image/room1.png',
    'src/image/room2.png',
    'src/image/room3.png'
  ])
}

const onClickLink = () => {
  router.push("/wallet")
};

const showVip = (name) => {

  // 根据vipType的值,确定用户会员名称和打折后的金额
  if (order.value.vipType === 1) {
    vipMessage.value = "年卡"
    discountPrice.value = (store.userRoom.hotelRoom.price) * 0.9
  } else if (order.value.vipType === 2) {
    vipMessage.value = "银卡"
    discountPrice.value = (store.userRoom.hotelRoom.price) * 0.8
  } else if (order.value.vipType === 3) {
    vipMessage.value = "金卡"
    discountPrice.value = (store.userRoom.hotelRoom.price) * 0.7
  } else {
    vipMessage.value = "普通用户"
    discountPrice.value = store.userRoom.hotelRoom.price
  }

  console.log(order.value.payType)
  // 保留2位小数
  formattedPrice.value = discountPrice.value.toFixed(2)

  showDialog({
    title: name,
    message: "您的vip等级为:" + vipMessage.value,
    theme: 'round-button',
  }).then(() => {
    showPay.value = true;
    // 初始化order数据
    order.value.roomId = store.userRoom.hotelRoom.id;
  })
}

const addPay = () => {
  // 初始化续费房间总金额
  order.value.price = parseFloat((formattedPrice.value * order.value.days).toFixed(2))
  // console.log(order.value.price)
  // console.log(order.value.payType)
  post("/hotel/room/renew",order.value).then(r => {
    // console.log("data"+JSON.stringify(r.data));
    if (r.code == 0) {
      // 成功 支付信息
      if (order.value.payType == 1) {
        store.setOrder(order.value.price, new Date().toLocaleDateString());
        router.push("/success")
      } else if (order.value.payType == 2) {
        document.write(r.data);
      }
    } else {
      showToast(r.data);
    }
  }).catch(function (){
    showToast("有异常")
  })

}

const changeRate = () => {
  post("/hotel/roomRate/change", roomRate.value).then(r=>{
    if (r.code==0) {
      showToast("评分修改成功")
    } else {
      showToast("评分修改失败")
    }
  }).catch(function () {
    showToast("有异常")
  })
}

const roomCollect = () => {
  const collectStatus = ref(0);
  console.log(JSON.stringify(checked))
  if (checked.value) {
    collectStatus.value = 1;
  } else if (!checked.value) {
    collectStatus.value = 0;
  }
  axios({
    method:'post',
    url:'http://localhost:8081/api/hotel/roomCollect/change',
    params:{
      collectStatus: collectStatus.value,
      roomId: store.userRoom.hotelRoom.id
    }
  }).then((data) => {
    // 接收响应数据,data封装了响应的数据
    const res = data.data;
    // console.log("data"+JSON.stringify(res.data));
    if (res.code == 0) {
      showToast(res.data)
    } else {
      showToast(res.data)
    }

  }).catch(function (){
    showToast("有异常")
  })
}

const onSubmit = () => {
  // 展示页面,初始化数据
  showVip(store.user.name)
}

onMounted(() => {
  // 进入页面时,获取当前用户对该房间的收藏状态
  axios({
    method:'post',
    url:'http://localhost:8081/api/hotel/roomCollect/getStatus',
    params:{
      roomId: store.userRoom.hotelRoom.id
    }
  }).then((data) => {
    // 接收响应数据,data封装了响应的数据
    const res = data.data;
    // console.log("data"+JSON.stringify(res.data));
    if (res.code == 0) {
      showNotify({ type: 'success', message: '期待您的续费' });
      if (res.data == 1) {
        checked.value = true;
      } else if (res.data == 0) {
        checked.value = false;
      }
    } else {
      showNotify({ type: 'warning', message: '展示失败' });
    }
  }).catch(function (){
    showToast("有异常")
  })

  // 获取登陆用户的数据
  get("/user/info").then(r=>{
    if (r.code==0) {
      store.user.name = r.data.account
    }
  }).catch(function (){
    showToast("有异常")
  })

  // 获取vip信息
  get("/user/vip/my").then(r=>{
    if(r.code==0){
      // 将查询到的vip信息传递给前端
      order.value.vipType = r.data.type
    }
  }).catch(function (){
    showToast("有异常")
  })

  // 获取用户对该房间的评分信息
  roomRate.value.roomId = store.userRoom.hotelRoom.id
  post("/hotel/roomRate/show",roomRate.value).then(r=>{
    if (r.code==0) {
      // 获取查询到的评分
      roomRate.value.rate = r.data
    } else {
      showToast("评分获取错误")
      roomRate.value.rate = 0.0;
    }
  }).catch(function () {
    showToast("有异常")
  })

})

</script>

<style scoped>

.dv-img {
  height: 250px;
  line-height: 300px;
  display: flex;
  justify-content: center;
}

.dv-swipeImg {
  height: 250px;
  line-height: 300px;
}

.dv-msg {
  padding: 10px;
}

.my-swipe {
  margin-bottom: 20px;
  .van-swipe-item {
    height: 250px;
    line-height: 300px;

    .swipe-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.cell_label {
  --van-cell-label-font-size: 20px
}

.img-icon {
  height: 20px;
}

</style>